const _ = require('lodash');
const services = require('../services');

const commonService = services.common;

module.exports = (app) => { // eslint-disable-line
  const { SysRole: roleModel, SysUserRoleMapping: userRoleMappingModel } = commonService.getModels();

  roleModel.registerResolver('requester', (role, context, callback) => {
    const employeeId = commonService.getEmployeeId();
    if (_.isEmpty(employeeId)) return callback(null, false);
    commonService.getCount(userRoleMappingModel, { userEmployeeId: employeeId, roleId: 1 }, (error, count) => callback(error, count != 0));
  });

  roleModel.registerResolver('admin', (role, context, callback) => {
    const employeeId = commonService.getEmployeeId();
    if (_.isEmpty(employeeId)) return callback(null, false);
    commonService.getCount(userRoleMappingModel, { userEmployeeId: employeeId, roleId: 3 }, (error, count) => callback(error, count != 0));
  });

  roleModel.registerResolver('approver', (role, context, callback) => {
    const employeeId = commonService.getEmployeeId();
    if (_.isEmpty(employeeId)) return callback(null, false);
    commonService.getList(userRoleMappingModel, { where: { userEmployeeId: employeeId }, include: 'role' }, (error, userRoleList) => {
      let isApprover = false;
      _.forEach(userRoleList, (userRoleItem) => {
        if (userRoleItem.role().isApprover) isApprover = true;
      });
      callback(error, isApprover);
    });
  });
};
